package com.beyondzy.shrio.realm;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.beyondzy.shrio.entity.AccountDO;
import com.beyondzy.shrio.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;


public class AccoutRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户的用户信息
        Subject subject = SecurityUtils.getSubject();
        AccountDO account = (AccountDO) subject.getPrincipal();

        //设置角色
        HashSet<String> roles = new HashSet<>();
        roles.add(account.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        //设置权限
        info.addStringPermission(account.getPerms());
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        AccountDO accountDO = accountService.lambdaQuery().eq(AccountDO::getUsername, token.getUsername()).one();
        if (ObjectUtils.isNotEmpty(accountDO)) {
            return new SimpleAuthenticationInfo(accountDO, accountDO.getPassword(), getName());
        }
        return null;
    }
}
